<template>
  <div class="order-management">
    <el-card>
      <!-- 操作栏 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="平台名称">
          <el-input v-model="searchForm.platformName" placeholder="请输入平台名称"></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="searchForm.consumerName" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.goodName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status">
            <el-option
              v-for="status in orderStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDeleteBatch">批量删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="uploadExcelDialog=true">导入</el-button>
          <el-button type="primary"  @click="downloadExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <!-- 数据展示层 -->
    <el-table :data="tableData" border
              style="width: 100%"
              @selection-change="handleSelectionChange"
              @row-click="handleEdit">
      <el-table-column type="selection" />
      <el-table-column prop="id" label="退货订单号" />
      <el-table-column prop="platformName" label="平台名称" />
      <el-table-column prop="consumerName" label="用户名称" />
      <el-table-column prop="goodName" label="商品名称" />
      <el-table-column prop="goodImageUrl" label="商品图片" >
        <template slot-scope="scope">
          <img :src="scope.row.goodImageUrl" alt="商品图片" style="max-width: 100%; max-height: 200px;" />
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额(元)" />
      <el-table-column prop="returnType" label="退货类型" />
      <el-table-column prop="returnReason" label="退货原因" />
      <el-table-column prop="returnWarehouse" label="退货仓库" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="getOrderStatusTagType(scope.row.status)"
            size="small"
          >{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '待审核'"
            size="mini"
            type="success"
            @click.stop="openAuditDialog(scope.row)"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--      新增/修改表单-->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="60%">
      <el-form :model="Editform" :rules="rules" ref="Editform" label-width="100px">
        <el-form-item label="平台" prop="platformName">
          <el-select v-model="Editform.platformName" placeholder="请选择供应商" style="width: 100%;">
            <el-option
              v-for="item in platformNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="consumerName">
          <el-input v-model="Editform.consumerName" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model="Editform.goodName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="goodImageUrl">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange"
            :limit="1">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- 预览图 -->
          </el-upload>
            <img :src="uploadedImagePreview || require('@/assets/images/default.png')" alt="预览图" style="max-width: 100%; max-height: 200px;" />
        </el-form-item>
        <el-form-item label="金额(元)" prop="amount">
          <el-input v-model.number="Editform.amount" placeholder="请输入金额"></el-input>
        </el-form-item>
        <el-form-item label="退货类型" prop="returnType">
          <el-select v-model="Editform.returnType" placeholder="请选择退货类型" style="width: 100%">
            <el-option
              v-for="item in returnTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="退货原因" prop="returnReason">
          <el-input v-model="Editform.returnReason" placeholder="请输入退货原因"></el-input>
        </el-form-item>
        <el-form-item label="退货仓库">
          <el-select v-model="Editform.returnWarehouse" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" v-if="title === '修改'">
          <el-select v-model="Editform.status" placeholder="请选择状态">
            <el-option
              v-for="status in orderStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="Editform.remark" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onClose">关 闭</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="订单审核" :visible.sync="auditDialogVisible" width="40%">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio label="待审核"></el-radio>
            <el-radio label="审核通过"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核理由" v-if="auditForm.auditResult === '审核通过'">
          <el-input v-model="auditForm.auditReason" type="textarea" :rows="3" placeholder="请输入审核理由"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="auditDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitAudit">提 交</el-button>
  </span>
    </el-dialog>

    <!-- 文件上传弹窗 -->
    <el-dialog title="上传文件" :visible.sync="uploadExcelDialog" width="30%">
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelFun"
        :on-change="handleFileChange"
      >
        <i class="el-icon-upload"></i>

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>

        <el-button type="primary" @click="">确 定</el-button>

      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15]"
      :page-size="queryPage.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
    />



  </div>
</template>

<script>
import {
  addOrderReturn,
   deleteOrderReturn,
  updateOrderReturn,
  findAllByPage,
  uploadExcel
} from '@/api/order/orderReturn'
import { uploadPicture } from '@/api/upload'
import { findAllWarehouseName } from '@/api/order/orderPurchase'
import { findAllPlatformName } from '@/api/order/orderPlatform'
export default {
  name: 'orderPlatform',
  data() {
    return {
      platformNameOptions:[],
      returnTypeOptions: [
        { label: '仅退款', value: '仅退款' },
        { label: '退款退货', value: '退款退货' },
        { label: '换货', value: '换货' },
        { label: '退款退货（包邮）', value: '退款退货（包邮）' }
      ],
      warehouseOptions:[],
      uploadExcelDialog:false,
      file: null,
      fileList: [],
      auditDialogVisible: false, // 控制审核弹窗显示
      auditForm: {
        auditResult: '待审核', // 审核结果，默认是待审核
        auditReason: ''        // 审核理由
      },
      currentRow: null,         // 当前正在审核的数据行
      uploadedImageFile: null, // 存储原始文件对象
      uploadedImagePreview: null, // 存储本地预览地址
      // 添加验证规则
      rules: {
        platformName: [
          { required: true, message: '平台名称不能为空', trigger: 'blur' }
        ],
        consumerName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        goodName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '金额不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字类型', trigger: 'blur' }
        ]
      },
      orderStatusOptions: [
        { value: '待买家退货', label: '待买家退货' },
        { value: '待平台收货', label: '待平台收货' },
        { value: '已完成', label: '已完成' },
        { value: '待审核', label: '待审核' }
      ],
      //复选框
      multipleSelection:[],
      title:'',
      dialogVisible:false,
      Editform: {},
      // 搜索栏
      searchForm:{
      },
      queryPage:{
        pageNum: 1,
        pageSize: 5
      },
      tableData: [],
      currentPage: 1,
      pageNum: 1,
      pageSize: 10,
      total: 0,
    }
  },
  created() {
    this.loadData();
  },

  methods: {
    getOrderStatusTagType(status){
      switch (status) {
        case '待买家退货':
        case '待审核':
          return 'warning'; // 黄色 tag
        case '待平台收货':
          return 'info'; // 灰色 tag
        case '已完成':
          return 'success'; // 绿色 tag
        default:
          return '';
      }
    },
    downloadExcel(){
      this.$confirm(`确定要下载Excel吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href="http://localhost:8888/order/return/download/excel"
        this.$message({
          message: '下载成功!',
          type: 'success',
          duration: 1200
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下载'
        });
      });
    },
    beforeUpload(){
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    uploadExcelFun() {
      const file = this.file;
      const formData = new FormData();
      formData.append('file', file);
      //封装文件上传的方法
      uploadExcel(formData).then(res => {
        if (res.code === 20000) {
          this.$message.success('上传成功');
          //上传成功后添加到文件列表
          this.fileList.push({
            name: file.name,
          });
          this.uploadExcelDialog = false;
          this.pageNum = 1;
          this.loadData()
        } else {
          this.$message.error(res.message || '上传失败');
        }
      })
    },
    handleFileChange(file) {
      this.file = file.raw;
    },
    submitAudit() {
      const { auditResult, auditReason } = this.auditForm;

      if (auditResult === '审核通过' && !auditReason.trim()) {
        this.$message.warning('请填写审核理由');
        return;
      }

      // 构造更新后的订单对象
      const updatedOrder = {
        ...this.currentRow,
        status: auditResult === '审核通过' ? '已完成' : this.currentRow.status,
        auditReason: auditReason
      };

      // 调用 API 更新订单状态
      updateOrderReturn(updatedOrder).then(res => {
        if (res.code === 20000) {
          this.$message.success('审核提交成功');
          this.auditDialogVisible = false;
          this.loadData(); // 刷新表格数据
        } else {
          this.$message.error(res.message || '审核失败');
        }
      }).catch(() => {
        this.$message.error('网络异常，请重试');
      });
    },
    openAuditDialog(row) {
      this.currentRow = { ...row }; // 复制当前行数据
      this.auditForm = {
        auditResult: '待审核',
        auditReason: ''
      };
      this.auditDialogVisible = true;
    },
    handleChange(file) {
      const rawFile = file.raw;
      if (!rawFile) return;
      // 只允许一个文件
      this.uploadedImageFile = rawFile;
      // 创建本地预览地址
      const previewUrl = URL.createObjectURL(rawFile);
      this.uploadedImagePreview = previewUrl;
    },
    // 关闭
    onClose(){
      this.dialogVisible = false
      this.Editform = {}
      this.uploadedImagePreview = null
      this.$refs.Editform.resetFields(); // 重置表单的验证状态
      this.handleReset()
    },
    // 批量删除
    handleDeleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('此操作将永久删除选中的文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        // distinguishCancelAndClose: true,    // 重要，设置为true才会把右上角X和取消区分开来
        // closeOnClickModal: false
      }).then(() => {// 用户点击确定进入此流程
        const ids = this.multipleSelection.join(',')
        deleteOrderReturn(ids)
          .then(ret => {
            if (ret.code === 20000) {
              this.$message.success('批量删除成功')
              this.queryPage.pageNum = 1
              this.loadData()
            }else{
              this.$message.error(ret.message || '删除失败')
            }
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    //select方法监控
    handleSelectionChange(val){
      this.multipleSelection = val.map(item => item.id)
    },
    // 新增/修改表单的提交
    onSubmit(){
      this.$refs.Editform.validate(valid => {
        if (!valid) {
          this.$message.error('请正确填写表单')
          return
        }
        if (this.uploadedImageFile) {
          const formData = new FormData();
          formData.append("file", this.uploadedImageFile);
          uploadPicture(formData).then(res => {
            console.log("res",res)
            if (res.code === 20000) {
              this.Editform.goodImageUrl = res.data; // 假设接口返回的图片路径是 res.data.url
              this.submitOrderForm(); // 提交订单数据
            } else {
              this.$message.error('图片上传失败');
            }
          }).catch(() => {
            this.$message.error('图片上传出错');
          });
        } else {
          this.submitOrderForm(); // 没有图片直接提交表单
        }
      });
    },
    // 实际提交订单的方法
    submitOrderForm() {
      if (this.title === '新增') {
        addOrderReturn(this.Editform).then(res => {
          if (res.code === 20000) {
            this.$message.success('添加成功');
            this.dialogVisible = false;
            this.loadData();
          } else {
            this.$message.error('添加失败');
          }
        });
      } else if (this.title === '修改') {
        updateOrderReturn(this.Editform).then(res => {
          if (res.code === 20000) {
            this.$message.success('修改成功');
            this.dialogVisible = false;
            this.loadData();
          } else {
            this.$message.error('修改失败');
          }
        });
      }
      // 清空图片缓存
      this.file = null;
      this.Editform.uploadedImagePreview = null;
    },
    //分页-页码大小改变
    handleSizeChange(newSize) {
      this.queryPage.pageSize = newSize
      this.loadData()
    },
    //分页-当前页码数改变
    handleCurrentChange(page){
      this.queryPage.pageNum = page;
      this.loadData();
    },
    // 加载数据
    loadData(){
      findAllByPage(this.queryPage).then(res=>{
        if(res.code == 20000){
          this.total = res.data.total
          this.tableData = res.data.list.map(item => ({
            ...item,
            goodImageUrl: `https://jinghaiyang.oss-cn-beijing.aliyuncs.com/app/upload/${item.goodImageUrl}`
          }))
        }else{
          this.$message.error(res.message);
        }
      })
      findAllWarehouseName().then(res=>{
        if(res.code == 20000){
          this.warehouseOptions = res.data.map(item => ({
            label: item,
            value: item
          }));
        }else{
          this.$message.error(res.message);
        }
      })
      findAllPlatformName().then(res=>{
        if(res.code == 20000){
          console.log(res)
          this.platformNameOptions = res.data.map(item => ({
            label: item,
            value: item
          }));
          console.log(this.platformNameOptions)
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //查询
    handleSearch(){
      // 构建查询参数
      const params = { ...this.searchForm,
        createTime: undefined };

      // 重置分页
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;

      // 处理时间范围
      if (this.searchForm.createTime?.length === 2) {
        params.startDate = this.searchForm.createTime[0];
        params.endDate = this.searchForm.createTime[1];
      }
      // 合并查询参数和分页参数
      this.queryPage = { ...this.queryPage, ...params};

      // 加载数据
      this.loadData();
    },
    //重置
    handleReset(){
      this.searchForm = {};
      this.queryPage = {};
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;
      this.Editform = {}
      this.uploadedImagePreview = null;
      this.loadData();
    },
    handleAdd(){
      this.title = '新增'
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.title = '修改';
      this.dialogVisible = true;
      this.Editform = row ;
      // 初始化上传预览图
      if (row.goodImageUrl) {
        this.uploadedImagePreview = row.goodImageUrl; // 显示原图
      } else {
        this.uploadedImagePreview = null;
      }
    },
    // 计算税金
    calculateTaxAmount() {
      const { quantity, unitPrice } = this.Editform;
      if (!quantity || !unitPrice) {
        this.Editform.taxAmount = '';
        return;
      }
      let subtotal = parseFloat(quantity) * parseFloat(unitPrice);
      if (subtotal < 2000) {
        this.Editform.taxAmount = subtotal.toFixed(2);
      } else {
        const taxableAmount = subtotal - 2000;
        const tax = taxableAmount * 0.015;
        this.Editform.taxAmount = (subtotal + tax).toFixed(2);
      }
    },
  },
  watch: {
    'Editform.quantity': function(newVal) {
      this.calculateTaxAmount();
    },
    'Editform.unitPrice': function(newVal) {
      this.calculateTaxAmount();
    }
  },
}
</script>


<style scoped lang="scss">
.order-management {
  padding: 20px；
}
</style>
